package com.singleton.demo07;

import java.util.Date;
import java.util.Random;

/**
 * 带有数据库缓存的多序列键生成器,还是单例模式,在内部使用一个集合存储多个序列键信息KeyInfo对象.
 * 该案例有个问题没解决: 效率和用keyName做锁会出现重复key值问题
 */
public class Client {
    private static String key1 = "key1";
    private static String key2 = "key2";

    public static void main(String[] args) {
        Random random = new Random(new Date().getTime());
        Integer num = 0;

        do{
            int abs = Math.abs(random.nextInt());
            if (abs%2==0) {
                num++;
                testCase1(num);
            }else{
                num++;
                testCase2(num);
            }
        }while (num < 11);
    }

    // 模拟订单序列键生成
    private static void testCase1(Integer num){
        new Thread(()->{
            KeyGenerator instance = KeyGenerator.getInstance();
            System.out.println(Thread.currentThread().getName()+"-------->key1------->"
                    + instance.getNextKey(key1));
        }).start();
    }

    // 模拟购物车商品序列键生成
    private static void testCase2(Integer num){
        new Thread(()->{
            KeyGenerator instance = KeyGenerator.getInstance();
            System.out.println(Thread.currentThread().getName()+"-------->key2------->"
                    + instance.getNextKey(key2));
        }).start();
    }
}
